package cerebrum.common;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import java.io.*;
import java.util.HashMap;
import java.util.Map;

/**
 * json配置write raed工具类
 */
public class FileUtil {
    /**
     * 将运行记录写入配置文件及用户设置
     * @param data
     */
    public static void writeFunctionRecord(HashMap<String, Object> data) {
        for (Map.Entry<String, Object> map : data.entrySet()) {
            ConfigPropertiesUtil.set(map.getKey(), String.valueOf(map.getValue()));
        }
    }
    /**
     * 读取图片数据源
     * @return
     */
    public static JSONObject readImagesDataSource() {
        String filePath = "setup/ImagesDataSource.json";
        return dataCheckAdapter(filePath);
    }

    public static boolean isJar() {
        return !(new File(PathUtils.getJarPath()).isDirectory());
    }

    private static JSONObject dataCheckAdapter(String fileName){
        if (isJar()){
            String data = PathUtils.readJarFile(fileName);
            return JSONObject.parseObject(data);
        }else {
            String fileInfoFromLocal = PathUtils.getFileInfoFromLocal(fileName);
            return JSONObject.parseObject(readJsonFile(fileInfoFromLocal));
        }
    }


    //读取json文件
    public static String readJsonFile(String fileName) {
        File jsonFile = new File(fileName);
        try (Reader reader = new InputStreamReader(new FileInputStream(jsonFile), "utf-8");){
            int ch = 0;
            StringBuilder sb = new StringBuilder();
            while ((ch = reader.read()) != -1) {
                sb.append((char) ch);
            }
            return sb.toString();
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }


}
